<template>
  <div class="sign_list">
    <div class="search">
      <div class="item" v-for="(item, index) in queryList" :key="index" :class="item.active ? 'active' : ''"
        @click="handleOpen(item.code)">
        {{ item.title }}
        <el-icon>
          <CaretBottom />
        </el-icon>
      </div>
    </div>

    <TeamInfo></TeamInfo>
    <div class="data_list" @scroll="handleScroll">
      <div class="data" v-for="(item, index) in dataList" :key="index">
        <div class="info">
          <div class="title">
            <div class="t">{{ item.match_name }} </div><span class="right" v-if="item.seasonname"> [{{ item.seasonname
              }}]</span>
          </div>
          <div class="attr">比赛时间 {{ item.begindate }}</div>
          <div class="attr">报名时间 {{ item.signdate }}</div>
        </div>
        <div class="item" v-for="(rowItem, index) in item.detail" :key="index">

          <div>
            <span class="state warning" v-if="rowItem.status == 0">审核中</span>
            <span class="state success" v-if="rowItem.status == 1">报名成功</span>
            <span v-if="rowItem.status == 2">
              <!--晋级确认截止-->
              <span class="state grey" v-if="rowItem.reject_reason == '晋级确认截止'">晋级确认截止</span>
              <span class="state success" v-else-if="rowItem.is_rise === 1">已确认晋级</span>
              <!--已晋级-->
              <span class=" state success" v-else>完赛</span>
            </span>
            <span class="state error" v-if="rowItem.status == 3">已取消/弃权</span>
            <span class="state warning" v-if="rowItem.status == 4">比赛中</span>
            <span v-if="rowItem.status == 5">
              <span class="state   grey" v-if="rowItem.reject_reason === '放弃晋级'">放弃晋级</span>
              <span class="state warning" v-else>已获晋级资格</span>
            </span>
            <!--2023.3.27号   完赛-> 晋级成功 -->
            <span class="state success" v-if="rowItem.status == 6">晋级成功</span>
            <span class="state error" v-if="rowItem.status == 7">弃权</span>
            <span class="state error" style="cursor: pointer; " v-if="rowItem.status == 8"
              @click="rowItem.reject_reason ? showRejectReason(rowItem.reject_reason) : ''">驳回
              {{ rowItem.reject_reason ? '(查看原因)' : '' }}</span>
            <span class="state warning" v-if="rowItem.status == 9">待确认</span>
            <span class="state  grey" v-if="rowItem.status == 10">报名未成功</span>
          </div>

          <div class="title">{{ rowItem.item_name }}</div>
          <div class="attr" v-if="rowItem.team_name">队伍名称：{{ rowItem.team_name }}</div>
          <div class="attr">
            <div> 组别：{{ rowItem.group_name }}</div>
            <div class="right">
              <div style="color: #e6a23c;"> 选手：</div>
              <div v-for="(rowItem, rowIndex) in splitName(rowItem.real_name, rowItem.ticket_url)" style="color: #e6a23c;">
                <a v-if="rowItem.pic" :href="rowItem.pic" style=" text-decoration: none;color: #e6a23c;font-weight: bold;" target="_blank"
                  class="a">{{ rowItem.name }}</a>
                <a v-else class="a" style="color: #e6a23c; font-weight: bold;">{{ rowItem.name }}</a>
              </div>
            </div>

          </div>
          <div class="btns">
            <el-button type="text" @click="handleInfo(rowItem.id, rowItem.status)">查看信息</el-button>
            <!-- <el-button type="text" @click="handleJiangInfo">获奖晋级信息</el-button>
            <el-button type="text">赛事成绩</el-button>
            <el-button type="text">获奖证书</el-button>
            <el-button type="text">赛事信息</el-button>
            <el-button type="text">赛事成绩</el-button> -->
            <el-button type="text" @click="handleNotice(rowItem); saveItemNoticeLog(rowItem.match_item_id, rowItem.id);"
              v-if="rowItem.notice_title">赛项通知
              <span class="red" v-if="rowItem.readCount == 0"></span>
            </el-button>
              <!--基础赛项开启了抽签功能、-->
            <el-button type="text"  @click="showDrawDialog(rowItem.id)"
            v-if="rowItem.is_draw == 1 &&rowItem.draw_open == 1 &&rowItem.sort == 0" >开始抽签</el-button>
            <el-button type="text" @click="showDrawResult(rowItem.sort)"
            v-if="rowItem.is_draw == 1 && rowItem.draw_open == 1 &&rowItem.sort > 0">抽签结果</el-button>


          </div>
        </div>
      </div>
    </div>
    <drawerSelect ref="dsRef" :title="currentSelect.title">
      <div class="drawer-select">
        <div v-for="(item, index) in currentSelect.items" :key="index" class="item" @click="handleSelect(item.code)"
          :class="item.code === currentSelect.value ? 'active' : ''">
          {{ item.name }} <el-icon color="#00A0E9"><Select /></el-icon>
        </div>
      </div>
    </drawerSelect>
  </div>

  <!--抽签弹窗-->
  <el-dialog v-model="drawVisible" :show-close="false" width="400px">
    <div class="confirm-dialog">
      <div class="image"></div>
      <div class="text">
        <!--动态显示随机数-->
        <div v-if="drawForm.drawNum == '0'">
          <!--<span style="color: #4cd964;font-size: 16px;font-weight: bold;" v-if="drawForm.randomNo>0">{{drawForm.randomNo}}</span>-->
          <span v-if="drawForm.randomNo != 0">正在抽签中，请点击确认抽出签号！</span>
          <span v-else>请点击确认，抽出签号</span>
        </div>
        <div v-else>抽签结果：<span style="color: #4cd964;font-size: 16px;font-weight: bold;">{{ drawForm.drawNum }}</span>
        </div>
      </div>
      <div class="btns">
        <el-button @click="drawVisible = false">关闭</el-button>
        <el-button type="primary" @click="drawhandle()"
          v-if="drawForm.drawNum == '0' && drawForm.btnShowFlag">确认</el-button>
      </div>
    </div>
  </el-dialog>

  <!--抽签结果-->
  <el-dialog v-model="drawResultVisible" :show-close="false" width="400px">
    <div class="confirm-dialog">
      <div class="image"></div>
      <div class="text">
        <!--动态显示随机数-->
        <div>抽签结果：<span style="color: #4cd964;font-size: 16px;font-weight: bold;">{{ drawForm.drawNum }}</span></div>
      </div>
      <div class="btns">
        <el-button @click="drawResultVisible = false">关闭</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from "vue";
import listService from "@/utils/listServiceWap";
import router from "@/router";
import baseService from "@/utils/baseService";
import { ElMessage, ElMessageBox } from "element-plus";
import { getCache } from "@/utils/cache";
import TeamInfo from "@/components/user/TeamInfo.vue";
import drawerSelect from "@/components/DrawerSelect.vue";
export default defineComponent({
  components: {
    drawerSelect,
    TeamInfo
  },
  setup() {
    const dsRef = ref()
    const state = reactive({
      getDataListURL: "/front/fast/match/matchRecord/page?pageSize=10",
      getDataListIsPage: true,
      deleteURL: "/pay/order",
      deleteIsBatch: true,
      dataForm: {
        city: '',
        season: '',
        matchLevel: '',
        province: '',
        beginDate: '',
        endDate: '',
        searchStr: '',
        noHistory: '1',
        itemType: ''
      },
      //数据分页
      page: 1,
      //触底加载数据判断
      refreshData: true,
      rejectReason: ''
    });
    return { ...listService(state), ...toRefs(state), dsRef };
  },

  data() {
    return {
      dataList: [{}, {}, {}, {}],
      queryList: [
        {
          title: "赛季", active: false, code: 'season', value: '', items: [{ name: "2023", code: "2023" }, { name: "2024", code: "2024" }, { name: "2025", code: "2025" }]
        },
        {
          title: "赛事层级", active: false, code: 'matchLevel', value: '', items: [{ name: "国赛", code: "1" }, { name: "省赛", code: "2" }, { name: "市赛", code: "3" }]
        },
        { title: "赛事地区", active: false, code: 'province', value: '' },
        { title: "赛事城市", active: false, code: 'city', value: '' },
        { title: "赛事类型", active: false, code: 'itemType', value: '' }
      ],
      currentSelect: {
        code: '1',
        title: '选择框',
        value: '北京',
        items: []
      },
      sessionList: [{ name: "2023", code: "2023" }, { name: "2024", code: "2024" }, { name: "2025", code: "2025" }],
      matchList: [{ name: "国赛", code: "1" }, { name: "省赛", code: "2" }, { name: "市赛", code: "3" }],
      matchArea: [{ name: "上海", code: "1" }, { name: "青岛", code: "2" }, { name: "济南", code: "3" }],
      areaCity: { code: '0', item: [] },
      area: { code: '0', item: [] },
      dates: null,
      dates1: null,
      dialogVisible: false,
      drawVisible: false,
      drawResultVisible: false,
      rejectReasonVisible: false,
      isCollapse: 1,
      isNavCollapse: false,
      showDialogFlag: false,
      evaluationDialogFlag: false,
      updateForm: {
        id: null,
        schoolName: '',
        evaluation: ''
      },
      drawForm: {
        id: null,
        drawNum: '0',
        randomNo: 0,
        btnShowFlag: true
      },

      formLabelWidth: '120px',
      userInfo: "",
      timer: 0,
      //数据上拉监听
      dataTimer:0,
      //是否有未读消息
      unreadFlag: false,
      scrollItem: { clientHeight: 0, scrollTop: 0, scrollHeight: 0 }
    };
  },
  mounted() {

    this.userInfo = getCache('userInfo', { isSessionStorage: true }, {});
    //延迟5秒执行
    setTimeout(() => {
      this.checkUnread();
    }, 5000);
    //获取滚动容器信息
    this.scrollItem = document.querySelector(".data_list")!;
    //查询一级城市
    baseService.areaList({ code: 0, }, (response: any) => {
      response.unshift({ code: "", name: "全部" });
      this.queryList[2].items = response;
    });
    //查询赛事类型
    baseService.get("/front/fast/dict/dictList/list?pid=100201").then((e: any) => {
      e.data.unshift({ code: "", name: "全部" });
      this.queryList[4].items = e.data;
    });

  },

  methods: {
    selectCity() {
      if (this.dataForm.province) {
        this.areaCity.code = this.dataForm.province;
        baseService.areaList(this.areaCity);
      } else {
        this.areaCity.item = [];
      }

    },
    handleInfo(id: any, status: number) {
      //router.push("/enroll/enrollInfo?id="+id);
      let typename = 'detail';
      //完赛
      if (status == 2) {
        typename = 'detail';
      } else {
        typename = 'edit';
      }
      router.push("/match/sign_up_info?id=" + id + "&status=" + status + "&typename=" + typename);
      //判断跳转到省赛

      //判断跳转到国赛
    },
    handleNotice(e: { match_item_id: number }) {
      router.push({ path: "/wap/notice/detail_info2", query: { id: e.match_item_id } });

    },
    //保存日志 saveItemNoticeLog
    saveItemNoticeLog(matchItemId: any, userId: any) {
      baseService.get("/front/notice/saveItemNoticeLog", {
        matchItemId: matchItemId,
        userId: userId
      }).then((e: any) => {
        if (e.code == '0') {
          console.log("保存日志成功");
        }
      });
    },
    cancel(id: any, status: number) {
      let msg = status == 1 ? "确认弃权？" : "确认取消报名？ 如需更新报名信息，请勿取消报名，请先在<a style='color: #00A0E9' >查看信息</a>中修改 ";
      let msg2 = status == 1 ? "弃权成功！" : "取消报名成功！";
      if (status == 5) {
        msg = "确认放弃晋级？";
        msg2 = "放弃晋级成功！";
      }
      ElMessageBox.confirm(msg, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true
      }).then(e => {

        baseService.post("/front/spmatchItemTeam/cancel", { id: id }).then((e: any) => {


          if (e.code == 0) {
            ElMessage.success(msg2);
          } else {
            ElMessage.error(e.msg);
          }

          this.query();
        });
      });

    }
    , handlePromotion() {
      router.push("/enroll/promotion");
    }, reset: function () {
      if (this.dataForm) {
        this.dataForm = {
          season: '',
          matchLevel: '',
          city: '',
          province: '',
          beginDate: '',
          endDate: '',
          searchStr: '',
          noHistory: '1',
          itemType: ''
        };

      }
    },
    /**
     * 申请晋级
     * @param id
     */
    risehandle(id: any, status: number) {
      //router.push("/enroll/enrollInfo?id=" + id + "&type=rise");
      router.push("/enroll/enrollInfo-detail?id=" + id + "&status=" + status + "&typename=edit");
    },
    /**
     * 确认晋级
     * @param id
     */
    confirmhandle(id: any, match_levl: string, typename: string) {
      router.push("/enroll/confirmEnrollInfo?id=" + id + "&type=rise");
    },
    /**
     * 赛项通知
     */
    noticehandle(id: any) {
      router.push({ path: "/notice/detail2", query: { id: id } });
    },

    /**
     * 弹出抽签
     */
    showDrawDialog(id: any) {
      this.drawForm.drawNum = '0';
      this.drawForm.randomNo = 0;
      this.drawForm.btnShowFlag = true;
      this.drawVisible = true;
      this.drawForm.id = id;
      //随机滚动
      this.randomNum();
    },

    /**
     * 抽签
     * @param id
     */
    drawhandle() {
      //清除定时器
      clearInterval(this.timer);
      //抽签号码重置-1 不展示出来
      this.drawForm.randomNo = -1;
      //隐藏确定按钮
      this.drawForm.btnShowFlag = false;
      //倒计时执行3s
      setTimeout(() => {
        baseService.get("/front/spmatchItemTeam/draw?id=" + this.drawForm.id).then((res: any) => {
          if (res.code == 0) {
            this.drawForm.drawNum = res.data;
            ElMessage.success('抽签成功');
            this.page=1;
            this.query();
          } else {
            ElMessage.error(res.msg);
          }
        })
      }, 3000);
    },

    /**
     * 按照顿号分割用户名
     */
    splitName(userName: string, entryPic: string) {
      if (!userName) return [];
      let names = userName.split("、");
      let pics = entryPic ? entryPic.split("、") : [];
      let arr = [];
      for (let i = 0; i < names.length; i++) {
        if (names.length == 1) {
          arr.push({ name: names[i], pic: pics[i] });
        } else {
          arr.push({ name: i < names.length - 1 ? names[i] + '、' : names[i], pic: pics[i] });
        }

      }
      return arr;

      let str = "";
      for (let i = 0; i < names.length; i++) {
        if (pics[i]) {
          str += '<a href=' + pics[i] + '>' + names[i] + '</a> 、';
        } else {
          str += names[i] + "、";
        }
      }
      return str;
    },
    //随机数跳动
    randomNum() {
      //定时器
      this.timer = setInterval(() => {
        let num = Math.floor(Math.random() * 200);
        this.drawForm.randomNo = num;
      }, 100);
    },
    //查看抽签结果
    showDrawResult(drawNum: any) {
      this.drawResultVisible = true;
      this.drawForm.drawNum = drawNum;
    },


    //弹出原因
    showRejectReason(reason: any) {
      this.rejectReason = reason;
      this.rejectReasonVisible = true;
    },

    /**
     * 查看是否有未读消息
     */
    checkUnread() {
      // 循环dataList,判断readCount=0表示有未读消息
      this.dataList.forEach((item: any) => {
        //再次循环item里的detail
        item.detail.forEach((item1: any) => {
          console.log('--------------', item.readCount)
          if (item1.readCount === '0') {
            this.unreadFlag = true;
          }
        });
      });
    },

    /**
     * 全部已读
     */
    allRead() {
      // 把上面的内容改为for循环
      for (let i = 0; i < this.dataList.length; i++) {
        for (let j = 0; j < this.dataList[i].detail.length; j++) {
          if (this.dataList[i].detail[j].readCount === '0') {
            this.saveItemNoticeLog(this.dataList[i].detail[j].match_item_id, this.dataList[i].detail[j].id);
          }
        }
      }

      // 重新加载列表
      this.query();
      // 全部已读后，把未读消息标识改为false
      this.unreadFlag = false;
    },
    handleScroll() {

      if (this.scrollItem.clientHeight + this.scrollItem.scrollTop > (this.scrollItem.scrollHeight - 100)) {
        clearTimeout(this.dataTimer);
        // 设置新的定时器，延迟执行逻辑
        this.dataTimer = setTimeout(() => {

          ++this.page;
          this.query();

        }, 50);

      }

    },
    //打开下拉
    handleOpen(code: string) {
      this.queryList.forEach((item: any) => {
        item.active = item.code === code;
        if (item.active) {
          this.currentSelect = item;
          if (item.item) {
            this.currentSelect.items = item.item;
          }
        }
      });
      this.dsRef.open();
    },

    //选中下拉框
    handleSelect(code: string) {
      this.currentSelect.items.forEach((item: any) => {
        if (item.code === code) {
          this.currentSelect.value = code === this.currentSelect.value ? '' : code;
        }
      })
      //如果是省份，进行查询城市
      if (this.currentSelect.code === 'province') {
        //清空城市
        this.queryList[3].value = '';
        if (this.currentSelect.value) {
          baseService.areaList({ code }, (response: any) => {
            response.unshift({ code: "", name: "全部" });
            this.queryList[3].items = response;
          });

        } else {
          this.queryList[3].items = [];
        }
      }

      this.assembleSelectData();
      this.dsRef.close();

    },
    /**
     * 组装顶部下拉数据
     */
    assembleSelectData() {
      this.dataForm.season = this.queryList[0].value;

      this.dataForm.matchLevel = this.queryList[1].value;

      this.dataForm.province = this.queryList[2].value;


      this.dataForm.city = this.queryList[3].value;


      this.dataForm.itemType = this.queryList[4].value;

      this.page = 1;
      this.query();
    }
  }
});
</script>

<style lang="scss" scoped>
@import "./style.scss";
</style>
